import { ViewLayer } from './../view/ViewConsts';
import { Camera, director, Director, _decorator } from "cc";
import { Singleton } from "../class_base/Singleton";
import { Loger } from "../loger/Loger";
import SceneBase from "./SceneBase";

const { ccclass, property } = _decorator;
const LoadingScene:string = "LoadingScene";
@ccclass
export default class SceneMgr extends Singleton {
    private _nextScene: string
    private _nextSceneOnLaunched: Function
    private _curScene: SceneBase = null;
    /**切换前的上一个场景 */
    private _lastScene: string;
    /**切换前的上一个场景 */
    public get lastScene(): string { return this._lastScene };
    public get curScene(): SceneBase {
        return this._curScene
    }
    public set curScene(v: SceneBase) {
        this._curScene = v
    }
    public get nextScene(): string {
        return this._nextScene
    }
    public get nextSceneOnLaunched(): Function {
        return this._nextSceneOnLaunched
    }

    public get mainCamera(): Camera { return this._curScene ? this._curScene.mainCamera : null }
    public get curSceneName(): string { return this._curScene ? this._curScene.sceneName : null; }

    public getCurScene<T extends SceneBase>(): T {
        if (!this._curScene) {
            return null;
        }
        return <T>this._curScene
    }
    public setCurScene(scene: SceneBase) {
        this._curScene = scene
    }
    
    public getUIRoot(rootName:ViewLayer){
        if (!this._curScene) {
            return null;
        }
        return this._curScene.getUIRoot(rootName);
    }

    //异步加载场景
    public changeSceneLoading(nextScene: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload) {
        this._lastScene = this._curScene.sceneName;
        this._curScene = null;
        this._nextScene = nextScene
        this._nextSceneOnLaunched = onLaunched
        let preLoadPromise = new Promise<void>(resolve => {
            director.preloadScene(LoadingScene,
                (completedCount, totalCount, item) => {
                    // Loger.log(completedCount, totalCount, item)
                },
                (error: any) => {
                    if (error) {
                        Loger.log("场景预加载完成:", error)
                    }
                    resolve()
                })
        })
        Promise.all([preLoadPromise]).then(() => {
            this.changeScene(LoadingScene, onLaunched);
        }).catch((res) => {
            Loger.log("场景初始化异常")
        })
    }
    //同步加载场景
    public changeScene(nextScene: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload) {
        this._curScene = null;
        director.loadScene(nextScene, onLaunched, onUnloaded);
    }

}
